<?php

// 
// This script adds up the results returned from a Yahoo Pipes scrape of the GoogleCode download page
// Sum is returned as a JSON object, to be inserted with jQuery
// 

// Sample call: http://joemaller.com/services/itransmogrify_download_counter.php?callback=?

$filename = 'itransmogrify_downloads.txt';

if ( !file_exists($filename) )  touch( $filename );  // file doesn't exists, create it

if ( time() - filemtime($filename) > 5 || time() - filemtime($filename) == 0 ):

    $c = curl_init();

    curl_setopt( $c,  CURLOPT_URL, 'http://pipes.yahoo.com/joemaller/googlecode_downloads?_render=php&project=itransmogrify' );
    curl_setopt( $c, CURLOPT_RETURNTRANSFER, 1 );

    $downloads = curl_exec( $c );
    $downloads = unserialize($downloads);

    curl_close( $c );

    if ( isset( $downloads['value']['items'] ) ):   // catch potential errors from Yahoo Pipes, no idea what they look like...
        foreach( $downloads['value']['items'] as $i):
            $a[] = $i['content'] ;
        endforeach;
    
        $total = max( array_sum( $a ), $total );

        file_put_contents ( $filename, $total );
    endif;
else:

    $total = file_get_contents( $filename );
    
endif;	

echo htmlspecialchars( $_GET['callback'] ) . '({ "downloads" : "' . $total . '" })';

?>